package com.uenpay.oem.ui.main;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.qyx.android.database.FriendDB;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.callback.FragmentCallBack;
import com.uenpay.im.callback.OnGetAllClassmate;
import com.uenpay.im.configuration.ShareData;
import com.uenpay.im.invokeitems.friends.GetFriends;
import com.uenpay.im.ui.old.activity.PushServiceConn;
import com.uenpay.im.ui.old.activity.group.GroupMangerHandler;
import com.uenpay.im.ui.talklist.TalkListFragment;
import com.uenpay.oem.R;
import com.uenpay.oem.common.AppConstant;
import com.uenpay.oem.receiver.Myreceiver;
import com.uenpay.oem.ui.main.finance.FinanceFragment;
import com.uenpay.oem.ui.main.home.HomeNewFragment;
import com.uenpay.oem.ui.main.my.MyFragment;
import com.uenpay.oem.ui.weipay.WeiPayActivity;
import com.uenpay.util.app.base.BaseActivity;
import com.uenpay.util.rx.RxBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = "/main/main")
public class MainActivity extends BaseActivity implements FragmentCallBack {

    private static final String TAG = "MainActivity";

    private GroupMangerHandler groupMangerHandler = new GroupMangerHandler();
    private MainActivity.updatemsgcountBroadcastReceiver mBroadcastReceiver = null;
    private List<Fragment> list = new ArrayList<>();

    private int index = 0;

    @BindView(R.id.vp_container)
    ViewPager mViewPager;

    @BindView(R.id.tab_1)
    RelativeLayout rlHomeTab;
    @BindView(R.id.tab_2)
    RelativeLayout rlFinanceTab;
    @BindView(R.id.tab_3)
    RelativeLayout rlPayTab;
    @BindView(R.id.tab_4)
    RelativeLayout rlFriendTab;
    @BindView(R.id.tab_5)
    RelativeLayout rlUserTab;

    ImageView ivHome;
    ImageView ivFinance;
    ImageView ivFriend;
    ImageView ivUser;
    TextView tvHome;
    TextView tvFinance;
    TextView tvPay;
    TextView tvFriend;
    TextView tvUser;
    TextView tvUnreadMsg;
    private int mCurrentTabId;
    private Myreceiver myreceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        isBackExit = true;
        super.onCreate(savedInstanceState);

        IMApplication.IS_REFRESH_TOP_MSG = true;
        if (savedInstanceState != null) {
            index = savedInstanceState.getInt("index");
        }
        setContactNewMsg();
        getMyGroups();
        setSwipeBackEnable(false);
        registreceiver();

    }

    private void registreceiver() {
        myreceiver= new Myreceiver();
        IntentFilter filter=  new IntentFilter();
        filter.addAction(AppConstant.BALANCE_CHANGER);
        registerReceiver(myreceiver,filter);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void initView(View view) {
        mCurrentTabId = rlHomeTab.getId();


        ivHome = (ImageView) rlHomeTab.findViewById(R.id.iv_icon);
        ivFinance = (ImageView) rlFinanceTab.findViewById(R.id.iv_icon);
        ivFriend = (ImageView) rlFriendTab.findViewById(R.id.iv_icon);
        ivUser = (ImageView) rlUserTab.findViewById(R.id.iv_icon);

        tvHome = (TextView) rlHomeTab.findViewById(R.id.tv_title);
        tvFinance = (TextView) rlFinanceTab.findViewById(R.id.tv_title);
        tvFriend = (TextView) rlFriendTab.findViewById(R.id.tv_title);
        tvUser = (TextView) rlUserTab.findViewById(R.id.tv_title);
        tvPay = (TextView) rlPayTab.findViewById(R.id.tv_title);

        ivHome.setImageResource(R.drawable.sel_main_tab_home);
        ivFinance.setImageResource(R.drawable.sel_main_tab_finance);
        ivFriend.setImageResource(R.drawable.sel_main_tab_friend);
        ivUser.setImageResource(R.drawable.sel_main_tab_user);

        tvHome.setText(R.string.title_main_tab_home);
        tvFinance.setText(R.string.title_main_tab_finance);
        tvPay.setText(R.string.title_main_tab_pay);
        tvFriend.setText(R.string.title_main_tab_friend);
        tvUser.setText(R.string.title_main_tab_user);

        tvUnreadMsg = (TextView) rlFriendTab.findViewById(R.id.unread_count);
        tvHome.setSelected(true);
        ivHome.setSelected(true);

        HomeNewFragment fragment1 = new HomeNewFragment();
        FinanceFragment fragment2 = new FinanceFragment();
        TalkListFragment fragment3 = new TalkListFragment();
        MyFragment fragment4 = new MyFragment();
        list.add(fragment1);
        list.add(fragment2);
        list.add(fragment3);
        list.add(fragment4);

        // 绑定Fragment适配器
        mViewPager.setAdapter(new SectionsPagerAdapter(getSupportFragmentManager(), list));
        mViewPager.setOffscreenPageLimit(4);
        // 滑动监听
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        tabClick(rlHomeTab);
                        break;
                    case 1:
                        tabClick(rlFinanceTab);
                        break;
                    case 2:
                        tabClick(rlFriendTab);
                        break;
                    case 3:
                        tabClick(rlUserTab);
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    @OnClick({R.id.tab_1, R.id.tab_2, R.id.tab_4, R.id.tab_5})
    public void tabClick(View view) {
        if (view.getId() == mCurrentTabId)
            return;
        resetSelectStatus();
        switch (view.getId()) {
            case R.id.tab_1:
                ivHome.setSelected(true);
                tvHome.setSelected(true);
                mViewPager.setCurrentItem(0);
                break;
            case R.id.tab_2:
                ivFinance.setSelected(true);
                tvFinance.setSelected(true);
                mViewPager.setCurrentItem(1);
                break;
            case R.id.tab_4:
                ivFriend.setSelected(true);
                tvFriend.setSelected(true);
                mViewPager.setCurrentItem(2);
                break;
            case R.id.tab_5:
                ivUser.setSelected(true);
                tvUser.setSelected(true);
                mViewPager.setCurrentItem(3);
                break;
            default:
                break;
        }
        mCurrentTabId = view.getId();

    }

    @OnClick(R.id.btn_center)
    public void weipayClick() {
        Intent it = new Intent(MainActivity.this, WeiPayActivity.class);
        startActivity(it);
    }

    private void resetSelectStatus() {
        ivHome.setSelected(false);
        ivFinance.setSelected(false);
        ivFriend.setSelected(false);
        ivUser.setSelected(false);
        tvHome.setSelected(false);
        tvFinance.setSelected(false);
        tvFriend.setSelected(false);
        tvUser.setSelected(false);
    }

    private void getMyGroups() {
        groupMangerHandler.getMyGroups(null);
    }

    @Override
    protected void onResumeFragments() {
        if (mBroadcastReceiver == null) {
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(BroadcastAction.ACTION_FRIENDS_REQUEST);
            intentFilter.addAction(BroadcastAction.MSG_ACTION);
            intentFilter.addAction(BroadcastAction.ACTION_CLEAR_MSG_COUNT);
            intentFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
            intentFilter.addAction(BroadcastAction.DISCOVER_UNREAD_COUNT_ACTION);
            mBroadcastReceiver = new updatemsgcountBroadcastReceiver();
            registerReceiver(mBroadcastReceiver, intentFilter);
        }

        super.onResumeFragments();
    }


    public class updatemsgcountBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String SYSTEM_DIALOG_REASON_KEY = "reason";
            final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
            final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

            if (intent.getAction().equals(BroadcastAction.ACTION_FRIENDS_REQUEST)) {
                int count = intent.getIntExtra("count", 0);
                Log.d(TAG, "收到朋友请求数量 " + count);
                if (count > 0) {
                    Message msg = myHandler.obtainMessage();
                    msg.what = 0;
                    msg.arg1 = count;
                    myHandler.sendMessage(msg);
                }
            } else if (intent.getAction().equals(BroadcastAction.MSG_ACTION)) {
                int count = intent.getIntExtra("count", 0);
                Log.d(TAG, "收到消息数量 " + count);
                String info = intent.getStringExtra("info");
                Message msg = myHandler.obtainMessage();
                msg.what = 1;
                msg.obj = info;
                msg.arg1 = count;
                myHandler.sendMessage(msg);
            } else if (intent.getAction().equals(BroadcastAction.ACTION_CLEAR_MSG_COUNT)) {
                Message msg = myHandler.obtainMessage();
                msg.what = 2;
                myHandler.sendMessage(msg);
            } else if (intent.getAction().equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
                if (reason != null) {
                    if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
                        IMApplication.IS_GET_ALL_FRIENDS = true;
                    } else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
                        IMApplication.IS_GET_ALL_FRIENDS = true;
                    }
                }
            } else if (intent.getAction().equals(BroadcastAction.DISCOVER_UNREAD_COUNT_ACTION)) {
                // setDynamicNewMsg();
            }
        }
    }

    /**
     * 获取服务器通讯录数据
     */
    private void getAllFriends() {

        OnGetAllClassmate onGetAllClassmate = new OnGetAllClassmate() {

            @Override
            public void onSucceeful(final GetFriends.getAllFriendResult result) {
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        boolean is_update = false;
                        if (result.friends != null && result.friends.size() > 0) {
                            FriendDB.updateFriends(result.friends);
                            is_update = true;
                        }
                        if (result.last_update_id > 0) {
                            IMApplication.config.setFriendLastUpdateId(result.last_update_id);
                        }

                        if (is_update) {
                            Intent intent = new Intent(BroadcastAction.ACTION_REFRESH_FRIEND);
                            sendBroadcast(intent);
                        }
                        IMApplication.IS_GET_ALL_FRIENDS = false;
                    }
                }).start();
            }

            @Override
            public void onFail() {

            }
        };
        IMApplication.getAllClassmate(onGetAllClassmate);

    }

    @Override
    protected void onResume() {
        super.onResume();
        // END
        // setDynamicNewMsg();
        ShareData.getInstance().setCurPage(IMApplication.PAGE.PAGE_NULL);
        ShareData.getInstance().setChatId("0");
        PushServiceConn.getInstance(IMApplication.getAppContext()).startChatService();

    }

    // 控制通讯录的刷新 添加好友信息 这里需要把消息传递给talk list fragment处理
    private void setContactNewMsg() {
        if (IMApplication.IS_GET_ALL_FRIENDS) {
            // getCustStatus();
            getAllFriends();
        }
        // 这里取的是第一个fragment 我们的消息是在聊天fragment的右上角图标上显示 按需进行修改
        // TextView unreadCount = (TextView)
        // mTabHost.getTabWidget().getChildTabViewAt(1).findViewById(R.id.unread_count);
        int count = IMApplication.config.getIsNewFriend();

        if (count > 0) {
            if (count <= 99) {
                tvUnreadMsg.setText(count + "");
            } else {
                tvUnreadMsg.setText("99+");
            }
            IMApplication.IS_GET_ALL_FRIENDS = false;
            tvUnreadMsg.setVisibility(View.VISIBLE);
            Intent intent = new Intent(BroadcastAction.SHOW_NEW_FRIENDS_ACTION);
            intent.putExtra("count", count + "");
            sendBroadcast(intent);
        } else {
            tvUnreadMsg.setVisibility(View.GONE);
        }
    }

    private void setDynamicNewMsg() {

        // final TextView unreadCount = (TextView)
        // mTabHost.getTabWidget().getChildTabViewAt(1).findViewById(R.id.unread_count);
        int dynamicUnreadNum = IMApplication.config.getDynamicUnreadMsgCount();
        String custid = IMApplication.config.getDynamicLastSendCustId();
        /** 动态最新发布者custId **/
        /** 动态未读消息数量 **/
        if (dynamicUnreadNum > 0) {
            if (dynamicUnreadNum <= 99) {
                tvUnreadMsg.setText(dynamicUnreadNum + "");
            } else {
                tvUnreadMsg.setText("99+");
            }
            tvUnreadMsg.setVisibility(View.VISIBLE);
        } else {
            tvUnreadMsg.setVisibility(View.GONE);
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        List<Fragment> list;

        public SectionsPagerAdapter(FragmentManager fm, List<Fragment> list) {
            super(fm);
            this.list = list;
        }

        @Override
        public Fragment getItem(int position) {
            return list.get(position);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return list.size();
        }
    }

    public Handler myHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0) {
                // 这一块控制联系人新消息
                // final TextView unreadCount = (TextView)
                // mTabHost.getTabWidget().getChildTabViewAt(0).findViewById(R.id.unread_count);
                int count = msg.arg1;

                // if (count > 0) {
                // count = MyApplication.config.getIsNewFriend() + count;
                // MyApplication.config.setIsNewFriend(count);
                // if (count <= 99) {
                // unreadCount.setText(count + "");
                // } else {
                // unreadCount.setText("99+");
                // }
                // Intent intent = new
                // Intent(BroadcastAction.SHOW_NEW_FRIENDS_ACTION);
                // intent.putExtra("count", count + "");
                // sendBroadcast(intent);
                // unreadCount.setVisibility(View.VISIBLE);
                // }
            } else if (msg.what == 1) {
                // 这一块控制联系人新消息
                int count = msg.arg1;
                // final TextView unreadCount = (TextView)
                // mTabHost.getTabWidget().getChildTabViewAt(1).findViewById(R.id.unread_count);
                if (count > 0) {
                    if (count <= 99) {
                        tvUnreadMsg.setText(count + "");
                    } else {
                        tvUnreadMsg.setText("99+");
                    }
                    tvUnreadMsg.setVisibility(View.VISIBLE);
                } else {
                    tvUnreadMsg.setVisibility(View.GONE);
                }
            } else if (msg.what == 2) {
                // final TextView unreadCount = (TextView)
                // mTabHost.getTabWidget().getChildTabViewAt(1).findViewById(R.id.unread_count);
                tvUnreadMsg.setVisibility(View.GONE);
            }
            return false;
        }
    });

    @Override
    public void updateTabMsg(FragmentCallBack.TABTYPE tabType, FragmentCallBack.REMINDTYPE remindType, int count) {
        if (tabType == FragmentCallBack.TABTYPE.TAB_TALK_MSG) {
            Message msg = myHandler.obtainMessage();
            msg.what = 1;
            msg.arg1 = count;
            myHandler.sendMessage(msg);
        } else if (tabType == FragmentCallBack.TABTYPE.TAB_CONTACTS) {
            // Message msg = myHandler.obtainMessage();
            // msg.what = 1;
            // msg.arg1 = count;
            // myHandler.sendMessage(msg);
        }
    }

    @Override
    protected void onDestroy() {
        if (mBroadcastReceiver != null) {
            unregisterReceiver(mBroadcastReceiver);
        }
        super.onDestroy();
       unregisterReceiver(myreceiver);
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(!isTaskRoot());
        IMApplication.IS_GET_ALL_FRIENDS = true;
    }

    public static void launch(Activity activity) {
        ARouter.getInstance().build("/main/main").navigation(activity);
    }
}
